<script>
import { mapState } from 'vuex'
import store from '@/store'
import { GetRoleListApi } from '@/request/role/role-api'
import { AddNewUserApi, GetUserByIDApi, UpdateUserApi } from '@/request/user/user-api'
import {
  validateAddUserAccount,
  validateAddUserIdNumber,
  validateAddUserName,
  validateAddUserPhone, validateAddUserRole
} from '@/utils/validate/add-user-validate'

export default {
  data () {
    return {
      userId: null,
      roleOption: [],
      userMessage: {
        id: null,
        sex: 1,
        name: '',
        account: '',
        phone: '',
        idNumber: '',
        role: ''
      },
      rules: {
        account: {
          require: true,
          validator: validateAddUserAccount,
          trigger: 'blur'
        },
        phone: {
          require: true,
          validator: validateAddUserPhone,
          trigger: 'blur'
        },
        name: {
          validator: validateAddUserName,
          trigger: 'blur'
        },
        idNumber: {
          validator: validateAddUserIdNumber,
          trigger: 'blur'
        },
        role: {
          validator: validateAddUserRole,
          trigger: 'change'
        }
      }
    }
  },
  computed: {
    listenIsVisible () {
      return store.state.userEditData.isVisible
    },
    listenEditUserId () {
      return store.state.userEditData.editUserId
    },
    ...mapState({
      editUserId: state => state.userEditData.editUserId,
      isVisible: state => state.userEditData.isVisible
    })
  },
  methods: {
    closeAdd () {
      store.commit('userEditData/changeIsVisible', false)
      store.commit('userEditData/changeEditUserId', null)
      this.userMessage = {
        id: null,
        sex: 1,
        name: '',
        account: '',
        phone: '',
        idNumber: '',
        roleName: ''
      }
      this.userId = null
      this.roleOption = []
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addUserFrom'].clearValidate()
      })
    },
    async getRoleList () {
      let res = await GetRoleListApi()
      if (res.code === 200) {
        this.roleOption = res.data
      }
    },
    async getUserMessageById (id) {
      let res = await GetUserByIDApi(id)
      if (res.code === 200) {
        this.userMessage = res.data
      }
    },
    handleAddUser (type) {
      this.$refs.addUserFrom.validate(valid => {
        //表单验证失败
        if (!valid) {
          //提示语
          this.$message.error('请完善信息')
          return false
        } else {
          if (type === 'edit') {
            this.$confirm('确认修改该用户信息吗?', '提示', {
              'confirmButtonText': '确定',
              'cancelButtonText': '取消',
              'type': 'warning'
            }).then(async () => {
              let res = await UpdateUserApi(this.userMessage)
              if (res.code === 200) {
                this.$message.success('修改成功！')
                this.closeAdd()
                this.$parent.init()
              } else {
                this.$message.error(res.msg)
              }
            }).catch(() => {
              this.$message.info('取消修改！')
            })
          } else if (type === 'add') {
            this.$confirm('确定添加该用户信息吗？', '提示', {
              'confirmButtonText': '确定',
              'cancelButtonText': '取消',
              'type': 'warning'
            }).then(async () => {
              let res = await AddNewUserApi(this.userMessage)
              if (res.code === 200) {
                this.$message.success('添加成功！')
                this.closeAdd()
                this.$parent.init()
              } else {
                this.$message.error(res.msg)
              }
            }).catch(() => {
              this.$message.error('取消添加')
            })
          }
        }
      })

    },
    handleAddContinue () {
      this.$refs.addUserFrom.validate(valid => {
        if (!valid) {
          //提示语
          this.$message.error('请完善信息')
          return false
          }
        this.$confirm('确定添加该用户信息吗？', '提示', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
          'type': 'warning'
        }).then(async () => {
          let res = await AddNewUserApi(this.userMessage)
          if (res.code === 200) {
            this.$message.success('添加成功！')
            this.$parent.init()
            //添加用户并继续添加
            this.userMessage = {
              id: null,
              sex: 1,
              name: '',
              account: '',
              phone: '',
              idNumber: '',
              roleName: ''
            }
          } else {
            this.$message.error(res.msg)
          }

        }).catch(() => {
          this.$message.error('取消添加')
        })
      })
    }
  },
  watch: {
    listenIsVisible: {
      immediate: true,
      handler (val, oldval) {
        if (val) {
          this.getRoleList()
        }
      }
    },
    listenEditUserId: {
      immediate: true,
      handler (val, oldval) {
        if (val) {
          this.userId = val
          this.getUserMessageById(val)
        }
      }
    }
  }
}
</script>

<template>

  <el-drawer
      :before-close="closeAdd"
      :visible.sync="isVisible"
      :with-header="false"
      size="88.5%"
      direction="rtl"
      custom-class="user-add-drawer"
      ref="drawer"

  >
    <div class="header">
      <el-page-header
          @back="closeAdd"
          :content="editUserId===null?'添加用户':'编辑用户'">
      </el-page-header>
    </div>
    <el-card style="margin: 0 auto" shadow="hover">
      <div class="user-add-input">
        <el-form ref="addUserFrom" :model="userMessage" :rules="rules" label-width="80px" label-position="right">
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="userMessage.name" autocomplete="false" clearable></el-input>
          </el-form-item>
          <el-form-item label="账号:" prop="account" :rules="this.userId===null?rules.account:[{require: false}]"
                        v-show="this.userId===null">
            <el-input v-model="userMessage.account" autocomplete="false" clearable></el-input>
          </el-form-item>
          <el-form-item label="性别:">
            <el-radio-group v-model="userMessage.sex">
              <el-radio-button :label=1>男</el-radio-button>
              <el-radio-button :label=0>女</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号:" prop="phone">
            <el-input v-model="userMessage.phone" autocomplete="false" clearable maxlength="11"></el-input>
          </el-form-item>
          <el-form-item label=" 身份证号:" prop="idNumber">
            <el-input v-model="userMessage.idNumber" autocomplete="false" clearable maxlength="18"></el-input>
          </el-form-item>
          <el-form-item label="权限:" prop="role">
            <el-select v-model="userMessage.role" autocomplete="false" placeholder="请选择">
              <el-option
                  v-for="item in roleOption"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
              >
                <span style="float: left">{{ item.roleName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roleCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
      </div>
      <el-divider></el-divider>
      <div class="user-add-drawer__footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" @click="handleAddUser(userId===null?'add':'edit')">
          {{ userId === null ? '保 存' : '修 改' }}
        </el-button>
        <el-button type="success" v-show="this.userId===null" @click="handleAddContinue">保存并继续添加</el-button>
      </div>
    </el-card>
  </el-drawer>
</template>

<style scoped lang="less">
.el-drawer {

  .el-drawer__body {
    background-color: #cccccc !important;

    .header {
      margin-top: 25px;
      margin-left: 15px;
    }

  }

  .el-card {
    position: absolute;
    left: 30px;
    right: 30px;
    top: 120px;

    .user-add-input {
      width: 500px;
      margin-left: 200px;
    }

    .user-add-drawer__footer {
      width: 500px;
      margin: 20px auto 50px auto;
    }

    .el-input {
      width: 222px;
    }

  }
}

/deep/ .el-drawer.rtl {
  background: #f8f8f8;
}

/deep/ .el-radio-button .el-radio-button__inner {
  padding: 10px 20px;
  font-size: 14px;
  width: 111px;
}

</style>
